﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using LitJson;
using MvCameraControl;
using OCR.Config;
using OCR.SystemThread;
using static DMC300Axis_IO.Function.DMC300_Info;

namespace OCR
{
    public partial class Template_Form : Form
    {
        public Template_Form()
        {
            InitializeComponent();
        }
        List<string> TemplateImageNames = new List<string>();
        public static List<List<Point>> pointsList = new List<List<Point>>();

        public static bool isLocalImg = false;
        public static bool isGetImg = false;

        public static Bitmap saveBitmap;

        public static Rectangle cropRect;

        public static Bitmap cameraRecvBitmap;
        private void Template_Form_Load(object sender, EventArgs e)
        {
            isRect = false;

            DirectoryInfo dir = new DirectoryInfo(@"TemplateInput");
            FileInfo[] fileInfo = dir.GetFiles();
            foreach (FileInfo item in fileInfo)
            {
                TemplateImageNames.Add(item.Name);
            }
            Template_pB.SizeMode = PictureBoxSizeMode.Zoom;
            Template_pB.BackgroundImageLayout = ImageLayout.Zoom;

            //LocalTemplateInfo.LocalTemplateInfoInitial();

            //@"TemplateInput\\TemplateOrigin.bmp"

            if (LocalTemplateInfo.path == null)
            {
                MessageBox.Show("模板图片信息为null");
            }

            if (LocalTemplateInfo.path!= null&&!File.Exists(LocalTemplateInfo.path))
            {
                MessageBox.Show("不存在本地模板图片");
            }


            if (File.Exists(LocalTemplateInfo.path))
            {
                saveBitmap=(Bitmap)Image.FromFile(LocalTemplateInfo.path);
                Template_pB.Image = saveBitmap;
                //AlgorithmModule.ImageHandleV2((Bitmap)Template_pB.Image);
                //AlgorithmModule_GPU.ImageHandleV2_Opencv((Bitmap)Template_pB.Image);
                //Template_pB.Image = Image.FromFile(LocalTemplateInfo.path);
                //AlgorithmModule.ImageHandleV2(LocalTemplateInfo.path);
                //Template_pB.Image = AlgorithmModule.RectPoints(Template_pB.Image, true);
                AlgorithmModule_GPU.ImageHandleV2_ByteArray((Bitmap)Template_pB.Image);
                Template_pB.Image = AlgorithmModule_GPU.RectPoints((Bitmap)Template_pB.Image, AlgorithmModule_GPU.pointsList);
                pointsList = AlgorithmModule_GPU.pointsList;

                InfoTB_01.Text = LocalTemplateInfo.Info01;
                InfoTB_02.Text = LocalTemplateInfo.Info02;
                InfoTB_03.Text = LocalTemplateInfo.Info03;
                InfoTB_04.Text = LocalTemplateInfo.Info04;
                InfoTB_05.Text = LocalTemplateInfo.Info05;
                InfoTB_06.Text = LocalTemplateInfo.Info06;

                infos.Clear();
                foreach (var item in LocalTemplateInfo.InfoList)
                {
                    infos.Add(item);
                }
                currPath = LocalTemplateInfo.path;

            }
            Console.WriteLine("width: "+(int.Parse(LocalTemplateInfo.rect_Right) - int.Parse(LocalTemplateInfo.rect_X)).ToString());
            cropRect = new Rectangle
                (int.Parse(LocalTemplateInfo.rect_X) * 2,
                int.Parse(LocalTemplateInfo.rect_Y) * 2,
                (int.Parse(LocalTemplateInfo.rect_Right) - int.Parse(LocalTemplateInfo.rect_X)) * 2,
                (int.Parse(LocalTemplateInfo.rect_Bottom) - int.Parse(LocalTemplateInfo.rect_Y)) * 2);


            radioButton1.Checked = true;
        }


        private bool isDrawing = false;
        private Point startPoint = Point.Empty;
        public static Rectangle rect = new Rectangle();
        Rectangle currRect = new Rectangle();
        private void Template_pB_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isDrawing = true;
                startPoint = e.Location;
                Template_pB.Invalidate();
            }
            if (e.Button == MouseButtons.Right)
            {
                //MessageBox.Show(isDrawing.ToString());
                isRect = false;
                rect = Rectangle.Empty;
                Template_pB.Invalidate(rect);
            }
        }
        private readonly double ratio = 1624.0 / 1240.0; // 固定比例16:9
        private void Template_pB_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (isDrawing)
                {
                    Point current = e.Location;
                    int dx = current.X - startPoint.X;
                    int dy = current.Y - startPoint.Y;
                    //根据比例调整宽高
                     int width, height;
                    if (Math.Abs(dx) > Math.Abs(dy * ratio))
                    {
                        width = dx;
                        height = (int)(width / ratio);
                    }
                    else
                    {
                        height = dy;
                        width = (int)(height * ratio);
                    }
                    //处理反向拖动
                     int x = startPoint.X;
                    int y = startPoint.Y;
                    if (dx < 0) x = current.X;
                    if (dy < 0) y = current.Y;
                    //确保宽高为正
                    width = Math.Abs(width);
                    height = Math.Abs(height);


                    //int x = e.X > startPoint.X ? startPoint.X : e.X;
                    //int y = e.Y > startPoint.Y ? startPoint.Y : e.Y;
                    //int width = Math.Abs(e.X - startPoint.X);
                    //int height = Math.Abs(e.Y - startPoint.Y);


                    rect = new Rectangle(x, y, width, height);
                    Template_pB.Invalidate();

                }
            }
        }

        private void Template_pB_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isDrawing = false;
                Console.WriteLine("rect.X: " + rect.X + " rect.Y: " + rect.Y + " rect.Width: " + rect.Width + " rect.Height: " + rect.Height);
                Console.WriteLine("rect.Location: " + rect.Location + " rect.Right: " + rect.Right + " rect.Left: " + rect.Left + " rect.Top: " + rect.Top + " rect.Bottom: " + rect.Bottom);
                Console.WriteLine("rect.X: " + rect.X*2 + " rect.Y: " + rect.Y*2 + " rect.Width: " + rect.Width * 2 + " rect.Height: " + rect.Height * 2);
                //Template_pB.Invalidate(); // 触发重绘以清除临时矩形  
                isRect = true;
            }
        }

        private void Template_pB_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawRectangle(new Pen(Color.Red, 4), rect);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Bitmap bitmap = new Bitmap(Template_pB.Image);

            Graphics graphics1 = Graphics.FromImage(bitmap);
            Console.WriteLine(((double)812 / 1624).ToString());
            double ratio_X = (double)812 / 1624;
            double ratio_Y = (double)620 / 1240;
            //Point point0 = new Point((int)(248 * ratio_X), (int)(331 * ratio_Y));
            //Point point1 = new Point((int)(531 * ratio_X), (int)(338 * ratio_Y));
            //Point point2 = new Point((int)(529 * ratio_X), (int)(397 * ratio_Y));
            //Point point3 = new Point((int)(246 * ratio_X), (int)(390 * ratio_Y));
            Point point0 = new Point((int)(248), (int)(331));
            Point point1 = new Point((int)(531), (int)(338));
            Point point2 = new Point((int)(529), (int)(397));
            Point point3 = new Point((int)(246), (int)(390));
            bool isInsideRect = true;
            Point[] points = new Point[] { point0, point1, point2, point3, };
            foreach (var item in points)
            {
                bool x = rect.X*2 <= item.X & item.X <= rect.Right * 2;
                bool y = rect.Y * 2 <= item.Y & item.Y <= rect.Bottom * 2;
                Console.WriteLine("x: "+x.ToString()+ "  y: " + y.ToString() + "  x&y: " + (x&y).ToString());
                Console.WriteLine(item.X + "   " + item.Y);
                if (!(x & y))
                {
                    isInsideRect=false;
                    break;
                }
            }
            Console.WriteLine("isInsideRect: " + isInsideRect);
            Pen pen = new Pen(Color.Red, 5);
            graphics1.DrawLines(pen, points);
            graphics1.DrawLine(pen, points[0], points[3]);
            Template_pB.Image = bitmap;
        }

        private void Template_Form_FormClosed(object sender, FormClosedEventArgs e)
        {
            isRect = false;
            rect = Rectangle.Empty;
            Template_pB.Invalidate(rect);
            //if (OCR_Form.softwareType == "0")
            //{
            //    CameraTriggerThread.iCameraTrigger_Step = 0;
            //}
            //else if(OCR_Form.softwareType == "1")
            //{
            //    if(OCR_Form.isModbusRealTimeStart)
            //        CameraTriggerThread_Modbus.iCameraTrigger_Step = 5;

            //}
            //CloseDevice();
            Console.WriteLine("Template_Form.isGrabbing: " + Template_Form.isGrabbing);
            //CameraReceiveThread.CameraInitialize();
            Console.WriteLine("CameraReceiveThread.isGrabbing: " + CameraReceiveThread.isGrabbing);
            if (CameraReceiveThread.isGrabbing)
            {
                CameraReceiveThread.device.Parameters.SetEnumValueByString("TriggerSource", "Line0");
            }
            Console.WriteLine("LocalInfo.imgScale:  " + LocalInfo.imgScale);
            OCR_Form.template_Form = null;

        }
        public static bool isRect=false;
        private void RectBtn_Click(object sender, EventArgs e)
        {
            isRect = true;
        }

        private void SaveTeBtn_Click(object sender, EventArgs e)
        {
            SaveTemplateImg();



            isRect = false;
            //rect = Rectangle.Empty;
            //Template_pB.Invalidate(rect);

        }
        List<bool> inside = new List<bool>();
        //模板识别  判断算法识别框是否在框选范围
        private void GetTeBtn_Click(object sender, EventArgs e)
        {
            Console.WriteLine("isGetImg： "+isGetImg);
            if (isGetImg)
            {

                Console.WriteLine("已进行模板或本地获取 " );
                if (isLocalImg)
                {
                    saveBitmap = (Bitmap)Image.FromFile(currPath);
                }
                else
                {
                    saveBitmap = (Bitmap)cameraRecvBitmap.Clone();
                }
            }
            else
            {
                if (LocalTemplateInfo.path == null || !File.Exists(LocalTemplateInfo.path))
                    return;

                saveBitmap = (Bitmap)Image.FromFile(LocalTemplateInfo.path);
            }
            string dateTime = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");

            switch (OCR_Form.softwareType)
            {
                case "0":
                    //AlgorithmModule.ImageHandleV2(saveBitmap);
                    //pointsList = AlgorithmModule.pointsList;

                    //AlgorithmModule_GPU.ImageHandleV2_Opencv(saveBitmap);
                    //pointsList = AlgorithmModule_GPU.pointsList;

                    //if (rect == Rectangle.Empty)
                    //    return;
                    //AlgorithmModule_GPU.ImageHandleV2_CropImg(saveBitmap, new Rectangle(rect.X * 2, rect.Y * 2, rect.Width * 2, rect.Height * 2), "out\\crop-" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fffffff") + ".bmp");// 
                    //pointsList = AlgorithmModule_GPU.finalPointList;

                    AlgorithmModule_GPU.ImageHandleV2_ByteArray(saveBitmap);
                    pointsList = AlgorithmModule_GPU.pointsList;
                    break;
                case "1":
                    Image tempImg = AlgorithmModule.CropImageNoRect_opencv_nousing(saveBitmap, new Rectangle(rect.X * 2, rect.Y * 2, rect.Width * 2, rect.Height * 2), "", "", LocalInfo.imgScale);
                    if (tempImg == null)
                    {
                        Console.WriteLine("裁剪区域无效");
                    }

                    pointsList = AlgorithmModule.convertList;
                    break;
            }




            if (isGetImg)
            {
                if (isLocalImg)
                {
                    saveBitmap = (Bitmap)Image.FromFile(currPath);
                }
                else
                {
                    saveBitmap = (Bitmap)cameraRecvBitmap.Clone();
                }
            }
            else
            {
                saveBitmap = (Bitmap)Image.FromFile(LocalTemplateInfo.path);
            }



            infos.Clear();
            inside.Clear();
            bool isInsideRect = true;
            Console.WriteLine("识别框个数：" + pointsList.Count);
            Console.WriteLine("rect.X: " + rect.X.ToString() + "  y: " + rect.Y.ToString());
            Console.WriteLine("rect.X: " + (rect.X*2).ToString() + "  y: " + (rect.Y*2).ToString());
            foreach (var item in pointsList)
            {
                Console.WriteLine(item.Count);
                foreach(var x in item)
                {

                    bool x_Inside = rect.X * 2 <= x.X & x.X <= rect.Right * 2;
                    bool y_Inside = rect.Y * 2 <= x.Y & x.Y <= rect.Bottom * 2;
                    Console.WriteLine("x: " + x_Inside.ToString() + "  y: " + y_Inside.ToString() + "  x&y: " + (x_Inside & y_Inside).ToString());
                    if (!(x_Inside & y_Inside))
                    {
                        isInsideRect=false;
                        break;
                    }
                    else
                    {
                        isInsideRect = true;
                    }
                }
                inside.Add(isInsideRect);
            }


            for (int i = 0; i < inside.Count; i++) 
            {
                if (inside[i])
                {
                    //Console.WriteLine(AlgorithmModule.currConfigs[i].text);
                    //infos.Add(AlgorithmModule.currConfigs[i].text);
                    infos.Add(AlgorithmModule_GPU.currConfigs[i].text);
                }
                else
                {
                    //infos.Add(string.Empty);
                }
            
            }
            Console.WriteLine("框选信息个数：" + infos.Count);
            for (int i = 0;i < infos.Count;i++)
            {
                Console.WriteLine("框选信息内容" + i + "：" + infos[i]);
            }
            InfoTB_01.Text = InfoTB_02.Text= InfoTB_03.Text= InfoTB_04.Text= InfoTB_05.Text= InfoTB_06.Text=string.Empty;
            if (infos.Count >= 1)
                InfoTB_01.Text = infos[0];
            if (infos.Count >= 2)
                InfoTB_02.Text = infos[1];
            if (infos.Count >= 3)
                InfoTB_03.Text = infos[2];
            if (infos.Count >= 4)
                InfoTB_04.Text = infos[3];
            if (infos.Count >= 5)
                InfoTB_05.Text = infos[4];
            if (infos.Count >= 6)
                InfoTB_06.Text = infos[5];

            currRect = rect;
            isRect = false;
            //rect = Rectangle.Empty;
            //Template_pB.Invalidate(rect);

            List<List<Point>> finalPointList = new List<List<Point>>();
            for (int i = 0; i < pointsList.Count; i++)
            {
                Console.WriteLine("inside_点数组: "+inside[i]);
                if (inside[i])
                {
                    finalPointList.Add(pointsList[i]);

                }
            }

            Console.WriteLine("cameraRecvBitmap:  " + cameraRecvBitmap);

            //Template_pB.Image = AlgorithmModule.RectPoints(saveBitmap, finalPointList);
            Template_pB.Image = AlgorithmModule_GPU.RectPoints(saveBitmap, finalPointList);


        }




        #region  相机
        static readonly DeviceTLayerType enumTLayerType = DeviceTLayerType.MvGigEDevice | DeviceTLayerType.MvUsbDevice
| DeviceTLayerType.MvGenTLGigEDevice | DeviceTLayerType.MvGenTLCXPDevice | DeviceTLayerType.MvGenTLCameraLinkDevice | DeviceTLayerType.MvGenTLXoFDevice;

        static List<IDeviceInfo> deviceInfoList = new List<IDeviceInfo>();
        public static IDevice device = null;

        public static bool isGrabbing = false;        // ch:是否正在取图 | en: Grabbing flag
        static Thread receiveThread = null;    // ch:接收图像线程 | en: Receive image thread

        public static IFrameOut frameForSave;                         // ch:获取到的帧信息, 用于保存图像 | en:Frame for save image
        public static readonly object saveImageLock = new object();
        // ch:显示错误信息 | en:Show error message
        public static void ShowErrorMsg(string message, int errorCode)
        {
            string errorMsg;
            if (errorCode == 0)
            {
                errorMsg = message;
            }
            else
            {
                errorMsg = message + ": Error =" + String.Format("{0:X}", errorCode);
            }

            switch (errorCode)
            {
                case MvError.MV_E_HANDLE: errorMsg += " Error or invalid handle "; break;
                case MvError.MV_E_SUPPORT: errorMsg += " Not supported function "; break;
                case MvError.MV_E_BUFOVER: errorMsg += " Cache is full "; break;
                case MvError.MV_E_CALLORDER: errorMsg += " Function calling order error "; break;
                case MvError.MV_E_PARAMETER: errorMsg += " Incorrect parameter "; break;
                case MvError.MV_E_RESOURCE: errorMsg += " Applying resource failed "; break;
                case MvError.MV_E_NODATA: errorMsg += " No data "; break;
                case MvError.MV_E_PRECONDITION: errorMsg += " Precondition error, or running environment changed "; break;
                case MvError.MV_E_VERSION: errorMsg += " Version mismatches "; break;
                case MvError.MV_E_NOENOUGH_BUF: errorMsg += " Insufficient memory "; break;
                case MvError.MV_E_UNKNOW: errorMsg += " Unknown error "; break;
                case MvError.MV_E_GC_GENERIC: errorMsg += " General error "; break;
                case MvError.MV_E_GC_ACCESS: errorMsg += " Node accessing condition error "; break;
                case MvError.MV_E_ACCESS_DENIED: errorMsg += " No permission "; break;
                case MvError.MV_E_BUSY: errorMsg += " Device is busy, or network disconnected "; break;
                case MvError.MV_E_NETER: errorMsg += " Network error "; break;
            }

            MessageBox.Show(errorMsg, "PROMPT");
        }
        //刷新设备列表
        private static void RefreshDeviceList()
        {
            // ch:创建设备列表 | en:Create Device List

            int nRet = DeviceEnumerator.EnumDevices(enumTLayerType, out deviceInfoList);
            if (nRet != MvError.MV_OK)
            {
                ShowErrorMsg("Enumerate devices fail!", nRet);
                return;
            }

            OpenDevice();
        }

        public static void OpenDevice()
        {
            //判断有无设备
            if (deviceInfoList.Count == 0)
            {
                ShowErrorMsg("No device, please select", 0);
                return;
            }

            // 获取选择的设备信息 
            IDeviceInfo deviceInfo = deviceInfoList[0];

            try
            {
                // 打开设备
                device = DeviceFactory.CreateDevice(deviceInfo);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Create Device fail!" + ex.Message);
                return;
            }


            int result = device.Open();
            if (result != MvError.MV_OK)
            {
                ShowErrorMsg("Open Device fail!", result);
                return;
            }

            //ch: 判断是否为gige设备 | en: Determine whether it is a GigE device
            if (device is IGigEDevice)
            {
                //ch: 转换为gigE设备 | en: Convert to Gige device
                IGigEDevice gigEDevice = device as IGigEDevice;

                // ch:探测网络最佳包大小(只对GigE相机有效) | en:Detection network optimal package size(It only works for the GigE camera)
                int optionPacketSize;
                result = gigEDevice.GetOptimalPacketSize(out optionPacketSize);
                if (result != MvError.MV_OK)
                {
                    ShowErrorMsg("Warning: Get Packet Size failed!", result);
                }
                else
                {
                    result = device.Parameters.SetIntValue("GevSCPSPacketSize", (long)optionPacketSize);
                    if (result != MvError.MV_OK)
                    {
                        ShowErrorMsg("Warning: Set Packet Size failed!", result);
                    }
                }
            }

            // ch:设置采集连续模式 | en:Set Continues Aquisition Mode
            //device.Parameters.SetEnumValueByString("AcquisitionMode", "Continuous");
            //device.Parameters.SetEnumValueByString("TriggerMode", "Off");
            device.Parameters.SetEnumValueByString("TriggerMode", "On");
            device.Parameters.SetEnumValueByString("TriggerSource", "Software"); //Software  Line0

            StartGrab();
        }
        public static void StartGrab()
        {
            try
            {
                // ch:标志位置位true | en:Set position bit true
                isGrabbing = true;

                receiveThread = new Thread(ReceiveThreadProcess);
                receiveThread.Start();
                //MessageBox.Show("抓取线程开启");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Start thread failed!, " + ex.Message);
                throw;
            }

            // ch:开始采集 | en:Start Grabbing
            int result = device.StreamGrabber.StartGrabbing();
            //MessageBox.Show("开始抓取");
            if (result != MvError.MV_OK)
            {
                isGrabbing = false;
                receiveThread.Join();
                ShowErrorMsg("Start Grabbing Fail!", result);
                return;
            }


        }
        public static void StopGrab()
        {
            // ch:标志位设为false | en:Set flag bit false
            isGrabbing = false;
            receiveThread.Join();

            // ch:停止采集 | en:Stop Grabbing
            int result = device.StreamGrabber.StopGrabbing();
            if (result != MvError.MV_OK)
            {
                ShowErrorMsg("Stop Grabbing Fail!", result);
            }
        }

        public static void CloseDevice()
        {
            // ch:取流标志位清零 | en:Reset flow flag bit
            if (isGrabbing == true)
            {
                StopGrab();
            }

            // ch:关闭设备 | en:Close Device
            if (device != null)
            {
                device.Close();
                device.Dispose();
            }
            SDKSystem.Finalize();
            // ch:控件操作 | en:Control Operation
            //SetCtrlWhenClose();
        }

        public static bool isImageData;
        public static DateTime imageDateTime;
        public static void ReceiveThreadProcess()
        {
            int nRet;

            Graphics graphics;   // ch:使用GDI在pictureBox上绘制图像 | en:Display frame using a graphics

            while (isGrabbing)
            {
                IFrameOut frameOut;


                nRet = device.StreamGrabber.GetImageBuffer(1000, out frameOut);

                if (MvError.MV_OK == nRet)
                {

                    lock (saveImageLock)
                    {

                        frameForSave = frameOut.Clone() as IFrameOut;
                        isImageData = true;

                        imageDateTime = DateTime.Now;

                    }

#if !GDI_RENDER
                    //device.ImageRender.DisplayOneFrame(OCR_Form.oCR_Form.mainCameraPb.Handle, frameOut.Image);

#else
                    // 使用GDI绘制图像
                    try
                    {
                        using (Bitmap bitmap = frameOut.Image.ToBitmap())
                        {
                            if (graphics == null)
                            {
                                graphics = pictureBox1.CreateGraphics();
                            }

                            Rectangle srcRect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
                            Rectangle dstRect = new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height);
                            graphics.DrawImage(bitmap, dstRect, srcRect, GraphicsUnit.Pixel);
                        }
                    }
                    catch (Exception e)
                    {
                        device.StreamGrabber.FreeImageBuffer(frameOut);
                        MessageBox.Show(e.Message);
                        return;
                    }
#endif


                    device.StreamGrabber.FreeImageBuffer(frameOut);
                }
                else
                {
                    //if (bnTriggerMode.Checked)
                    //{
                    //    Thread.Sleep(5);
                    //}
                }
            }
        }
        #endregion

        List<string> infos = new List<string>();
        public static DateTime grabImgTime;
        //相机取图显示  保存原图
        private void GetTemplateImgBtn_Click(object sender, EventArgs e)
        {
            isLocalImg = false;
            isGetImg = true;
            if (!CameraReceiveThread.isGrabbing)
            {
                CameraReceiveThread.CameraInitialize();
            }
            Console.WriteLine("CameraReceiveThread.isGrabbing: "+CameraReceiveThread.isGrabbing);
            Console.WriteLine("isGrabbing: " + isGrabbing);
            //OpenDevice();//打开相机

            //StartGrab();//开始抓图
            if (!CameraReceiveThread.isGrabbing)
                return;

            if (OCR_Form.softwareType == "0")
            {
                //相机软触发
                CameraReceiveThread.device.Parameters.SetEnumValueByString("TriggerSource", "Software");
                int result1 = CameraReceiveThread.device.Parameters.SetCommandValue("TriggerSoftware");
                if (result1 != MvError.MV_OK)
                {
                    CameraReceiveThread.ShowErrorMsg("Trigger Software Fail!", result1);
                }
                CameraTriggerThread_Template.iCameraTrigger_Step = 5;
                grabImgTime = DateTime.Now;
                Console.WriteLine("模板窗口开始获取图片信息");
                //Thread.Sleep(50);
                Console.WriteLine("软触时间" + DateTime.Now.Millisecond);
                Console.WriteLine("软触一次" + Template_Form.isImageData);
            }
            else
            {
                //Modbus单张触发
                OCR_Form.ModbusSingleTrigger();
            }
            //相机软触发
            //CameraReceiveThread.device.Parameters.SetEnumValueByString("TriggerSource", "Software");
            //int result = CameraReceiveThread.device.Parameters.SetCommandValue("TriggerSoftware");
            //Console.WriteLine(result);
            //if (result != MvError.MV_OK)
            //{
            //    CameraReceiveThread.ShowErrorMsg("Trigger Software Fail!", result);
            //}
            
            //CameraTriggerThread_Template.iCameraTrigger_Step = 5;
            //grabImgTime = DateTime.Now;
            //Console.WriteLine("模板窗口开始获取图片信息");
            //Thread.Sleep(50);
            //Console.WriteLine("软触时间" + DateTime.Now.Millisecond);
            //Console.WriteLine("软触一次" + Template_Form.isImageData);
            //AlgorithmModule.ImageHandleV2_Template();

            //try
            //{
            //    if (Template_Form.frameForSave == null)
            //    {
            //        Console.WriteLine("存图时无图像信息");
            //        return;
            //    }

            //    ImageFormatInfo imageFormatInfo = new ImageFormatInfo();
            //    imageFormatInfo.FormatType = ImageFormatType.Bmp;
            //    string ImagePath = @"TemplateInput\\TemplateOrigin.bmp";
            //    Template_Form.device.ImageSaver.SaveImageToFile(ImagePath, Template_Form.frameForSave.Image, imageFormatInfo, CFAMethod.Equilibrated);
            //    currPath = ImagePath;
            //}
            //catch (Exception ex)
            //{
            //    throw (ex);
            //}


            //pointsList = AlgorithmModule.pointsList;

            //if (AlgorithmModule.currConfigs.Count >= 1)
            //    InfoTB_01.Text = AlgorithmModule.currConfigs[0].text;
            //if (AlgorithmModule.currConfigs.Count >= 2)
            //    InfoTB_02.Text = AlgorithmModule.currConfigs[1].text;
            //if (AlgorithmModule.currConfigs.Count >= 3)
            //    InfoTB_03.Text = AlgorithmModule.currConfigs[2].text;
            //if (AlgorithmModule.currConfigs.Count >= 4)
            //    InfoTB_04.Text = AlgorithmModule.currConfigs[3].text;
            //if (AlgorithmModule.currConfigs.Count >= 5)
            //    InfoTB_05.Text = AlgorithmModule.currConfigs[4].text;
            //if (AlgorithmModule.currConfigs.Count >= 6)
            //    InfoTB_06.Text = AlgorithmModule.currConfigs[5].text;


            //CloseDevice();
        }

        public string OpenImageWithDialog()
        {
            string path;
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "图片文件|*.jpg;*.jpeg;*.png;*.bmp;*.gif";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        Console.WriteLine("openFileDialog.FileName: " + openFileDialog.FileName);
                        //return new Bitmap(openFileDialog.FileName);
                        openFileDialog.Dispose();
                        return openFileDialog.FileName;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"无法打开文件: {ex.Message}");
                        return null;
                    }
                }

            }
            return null;
        }
        public static string currPath;
        private void GetLocalImgBtn_Click(object sender, EventArgs e)
        {
            isLocalImg = true;
            isGetImg = true;
            Console.WriteLine("rect.Width: "+rect.Width);

            Console.WriteLine(rect==Rectangle.Empty);
            //cropRect = new Rectangle(rect.X * 2, rect.Y * 2, rect.Width * 2, rect.Height * 2);
            //cropRect = new Rectangle(x: 216, y: 440, width: 800, height: 446);
            //rect = Rectangle.Empty;
            //Template_pB.Invalidate(rect);

            string path = OpenImageWithDialog();

            if (path == null)
                return;
            currPath = path;
            Console.WriteLine("Template_Form.isRect: " + Template_Form.isRect);

            //saveBitmap = (Bitmap)Image.FromFile(path);
            //Template_pB.Image = saveBitmap;
            //AlgorithmModule.ImageHandleV2((Bitmap)Template_pB.Image);
            //Template_pB.Image = AlgorithmModule.RectPoints(Template_pB.Image, false);
            //pointsList = AlgorithmModule.pointsList;

            saveBitmap = (Bitmap)Image.FromFile(path);
            Template_pB.Image = saveBitmap;

            switch (OCR_Form.softwareType)
            {
                case "0":
                    //AlgorithmModule.ImageHandleV2(path);
                    //AlgorithmModule_GPU.ImageHandleV2_Opencv((Bitmap)Image.FromFile(path));
                    AlgorithmModule_GPU.ImageHandleV2_ByteArray((Bitmap)Image.FromFile(path));
                    break;
                case "1":
                    AlgorithmModule.ImageHandleV2_Opencv(path);
                    break;
            }

            //Template_pB.Image = AlgorithmModule.RectPoints(saveBitmap, AlgorithmModule.pointsList);
            //pointsList = AlgorithmModule.pointsList;

            Template_pB.Image = AlgorithmModule_GPU.RectPoints(saveBitmap, AlgorithmModule_GPU.pointsList);
            pointsList = AlgorithmModule_GPU.pointsList;

            //if (isRect)
            //{
            //    Console.WriteLine("cropRect: " + cropRect);
            //    Console.WriteLine("cropRectpath: " + path);
            //    AlgorithmModule.CropImageNoRect(new Bitmap(path), new Rectangle(rect.X*2,rect.Y*2,rect.Width*2,rect.Height*2), "cropTest.bmp");
            //    //AlgorithmModule.ImageHandleV2_Zoom(new Bitmap(path), cropRect, 2);
            //    Template_pB.Image = AlgorithmModule.RectPoints(new Bitmap(path), AlgorithmModule.convertList);
            //    saveBitmap = new Bitmap(path);
            //    //Template_pB.Image = saveBitmap;
            //    pointsList = AlgorithmModule.convertList;



            //}
            //else
            //{
            //    saveBitmap = (Bitmap)Image.FromFile(path);
            //    Template_pB.Image = saveBitmap;
            //    AlgorithmModule.ImageHandleV2((Bitmap)Template_pB.Image);
            //    Template_pB.Image = AlgorithmModule.RectPoints(Template_pB.Image, false);
            //    pointsList = AlgorithmModule.pointsList;
            //}

            InfoTB_01.Text = InfoTB_02.Text = InfoTB_03.Text = InfoTB_04.Text = InfoTB_05.Text = InfoTB_06.Text = string.Empty;

            if (AlgorithmModule_GPU.currConfigs.Count >= 1)
                InfoTB_01.Text = AlgorithmModule_GPU.currConfigs[0].text;
            if (AlgorithmModule_GPU.currConfigs.Count >= 2)
                InfoTB_02.Text = AlgorithmModule_GPU.currConfigs[1].text;
            if (AlgorithmModule_GPU.currConfigs.Count >= 3)
                InfoTB_03.Text = AlgorithmModule_GPU.currConfigs[2].text;
            if (AlgorithmModule_GPU.currConfigs.Count >= 4)
                InfoTB_04.Text = AlgorithmModule_GPU.currConfigs[3].text;
            if (AlgorithmModule_GPU.currConfigs.Count >= 5)
                InfoTB_05.Text = AlgorithmModule_GPU.currConfigs[4].text;
            if (AlgorithmModule_GPU.currConfigs.Count >= 6)
                InfoTB_06.Text = AlgorithmModule_GPU.currConfigs[5].text;
        }

        public string templateImgPath;
        private void SaveTemplateImg()
        {
            // 检查图片是否存在
            if (saveBitmap == null)
            {
                MessageBox.Show("没有可保存的图片！");
                return;
            }

            using (SaveFileDialog saveDialog = new SaveFileDialog())
            {
                // 配置保存对话框
                saveDialog.Title = "保存图片";
                saveDialog.Filter = "BMP 图片|*.bmp|JPEG 图片|*.jpg|PNG 图片|*.png|所有文件|*.*";
                saveDialog.DefaultExt = "jpg";
                saveDialog.AddExtension = true;

                string dateTime = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fff");
                saveDialog.FileName = dateTime;

                // 显示对话框并处理结果
                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        // 根据扩展名选择保存格式
                        string extension = Path.GetExtension(saveDialog.FileName).ToLower();
                        ImageFormat format = ImageFormat.Jpeg; // 默认格式

                        switch (extension)
                        {
                            case ".png":
                                format = ImageFormat.Png;
                                break;
                            case ".bmp":
                                format = ImageFormat.Bmp;
                                break;
                                // JPEG和其他格式使用默认处理
                        }
                        Console.WriteLine(saveDialog.FileName);
                        string targetPath = saveDialog.FileName;
                        //string uniquePath = GenerateUniquePath(targetPath);  // 生成唯一路径
                        //Console.WriteLine(uniquePath);


                        using (saveBitmap)
                        {
                            using (var newBitmap = new Bitmap(saveBitmap.Width, saveBitmap.Height))
                            {
                                using (var graphics = Graphics.FromImage(newBitmap))
                                {
                                    graphics.DrawImage(saveBitmap, 0, 0);
                                    saveBitmap.Dispose();
                                    Bitmap finalBitmap = AlgorithmModule_GPU.ConvertTo8bpp(newBitmap);
                                    // 保存图片
                                    finalBitmap.Save(targetPath, format);
                                    //saveBitmap.Save(targetPath);
                                    templateImgPath = targetPath;
                                    MessageBox.Show("图片保存成功！");
                                    graphics.Dispose();
                                    saveBitmap = (Bitmap)Image.FromFile(targetPath);
                                }


                            }
                        }

                        LocalTemplateInfo.rect_X = currRect.X.ToString();
                        LocalTemplateInfo.rect_Y = currRect.Y.ToString();
                        LocalTemplateInfo.rect_Right = currRect.Right.ToString();
                        LocalTemplateInfo.rect_Bottom = currRect.Bottom.ToString();

                        LocalTemplateInfo.path = templateImgPath;

                        LocalTemplateInfo.Info01 = LocalTemplateInfo.Info02 = LocalTemplateInfo.Info03 = LocalTemplateInfo.Info04 = LocalTemplateInfo.Info05 = LocalTemplateInfo.Info06 = string.Empty;
                        if (infos.Count >= 1)
                            LocalTemplateInfo.Info01 = infos[0];
                        if (infos.Count >= 2)
                            LocalTemplateInfo.Info02 = infos[1];
                        if (infos.Count >= 3)
                            LocalTemplateInfo.Info03 = infos[2];
                        if (infos.Count >= 4)
                            LocalTemplateInfo.Info04 = infos[3];
                        if (infos.Count >= 5)
                            LocalTemplateInfo.Info05 = infos[4];
                        if (infos.Count >= 6)
                            LocalTemplateInfo.Info06 = infos[5];

                        LocalTemplateInfo.LocalTemplateInfoSave(infos);

                        cropRect = new Rectangle
    (int.Parse(LocalTemplateInfo.rect_X) * 2,
    int.Parse(LocalTemplateInfo.rect_Y) * 2,
    (int.Parse(LocalTemplateInfo.rect_Right) - int.Parse(LocalTemplateInfo.rect_X)) * 2,
    (int.Parse(LocalTemplateInfo.rect_Bottom) - int.Parse(LocalTemplateInfo.rect_Y)) * 2);

                        OCR_Form.SetLocalTemplateInfos();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"保存失败：{ex.Message}");
                    }
                }
            }
        }

        // 生成唯一文件名（时间戳）
        private string GenerateUniquePath(string originalPath)
        {
            if (!File.Exists(originalPath)) return originalPath;

            string dir = Path.GetDirectoryName(originalPath);
            string fileName = Path.GetFileNameWithoutExtension(originalPath);
            string ext = Path.GetExtension(originalPath);
            string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
            return Path.Combine(dir, $"{fileName}_{timestamp}{ext}");
        }

        public static int imgScale;
        private void scaleTB_TextChanged(object sender, EventArgs e)
        {
            //int.TryParse(scaleTB.Text,out LocalInfo.imgScale);

            //Console.WriteLine("imgScale:  "+ imgScale);
            //Console.WriteLine("imgScale_int:  " + (int)imgScale);
            //imgScale = float.Parse(scaleTB.Text);
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton1.Checked)
            {
                LocalInfo.imgScale = 1;
                //imgScale = 1;
                Console.WriteLine("LocalInfo.imgScale:  " + LocalInfo.imgScale);
            }
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton2.Checked)
            {
                LocalInfo.imgScale = 2f;
                Console.WriteLine("LocalInfo.imgScale:  " + LocalInfo.imgScale);
            }
        }

        private void radioButton3_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton3.Checked)
            {
                LocalInfo.imgScale = 2.5f;
                Console.WriteLine("LocalInfo.imgScale:  " + LocalInfo.imgScale);
            }

        }

        private void radioButton4_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton4.Checked)
            {
                LocalInfo.imgScale = 3f;
                Console.WriteLine("LocalInfo.imgScale:  " + LocalInfo.imgScale);
            }
        }
    }
}
